package gosnoopers.fr;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import lazy_listview.ImageLoader;
import lazy_listview.JSONfunctions;
import listview.CountriesAdapterDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import common.Common;

public class FormFirst extends Activity {
	private Button btn_selecte_age, btn_selecte_language, btn_selecte_country,
			btn_selecte_province, btn_sign_up,btn_case_file;
	public static Dialog ageDialog, ageDialogLanguage, dialogCountry,dialogCasefile,
			dialogProvince;
	private Button btClose;
	private TextView text_view_landing_page_header;
	ListView listView, listViewLanguage, listviewCountry, listviewProvince,listviewCasefile;
	public static String URLCITIES = "";
	public static LinearLayout layoutBottomPP;
	public static Button txt_date;
	public static EditText _disparition_add;

	public static String amberalert = null;
	public static String dis_date = null;
	public static String disparition_add = null;
	public static String circonstance_miss = null;
	public static String name = null;
	public static String first_name = null;
	public static String nick_name = null;
	public static String age = null;
	public static String language = "3";
	public static String hair_color = null;
	public static String eyes_colors = null;
	public static String character = null;
	public static String any_health_condition = null;
	public static String handicap = null;
	public static String transport = null;
	public static String any_scars = null;
	public static String tattoo = null;
	public static String something_special = null;
	public static String defferent_interest = null;
	public static String life_style = null;
	public static String p_weight = "0";
	public static String p2_weight = "0";
	public static String k_weight = "0";
	public static String k2_weight = "0";
	public static String f_tall = null;
	public static String f2_tall = null;
	public static String m2_tall = null;
	public static String m_tall = null;
	public static String date_r = null;
	public static String author = "31";
	public static String countries_id = null;
	public static String province_id = null;
	public static String facebook = null;
	public static String case_file_tmp = "case "+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	public static String latitude = "atitude";
	public static String address = "Google Maps";
	public static String longtitude = "Longtitude";
	public static String id_image = "";
	private static String txt_case_file;
	public static boolean isUpdate = false;
	
	final Context context = this;
	ArrayList<HashMap<String, String>> arraylistCountries;
	public static JSONObject jsonobjectCountries;
	public static JSONArray jsonarrayCountries;
	ListView listCountries;
	CountriesAdapterDialog adapterCountries;
	public static String[] valuesageCountry = new String[] { "AAAA" };
	public static ArrayList<String> arrCountryId = new ArrayList<String>();

	ArrayList<HashMap<String, String>> arraylistCities;
	public static JSONObject jsonobjectCities;
	public static JSONArray jsonarrayCities;
	ListView listCities;
	CountriesAdapterDialog adapterCities;
	public static String[] valuesageCities = new String[] { "BBB" };
	public static ArrayList<String> arrCitiesId = new ArrayList<String>();
	
	ArrayList<HashMap<String, String>> arraylistCasefile;
	public static JSONObject jsonobjectCasefile;
	public static JSONArray jsonarrayCasefile;
	public static JSONArray aPhotoForm;
	ListView listCasefile;
	CountriesAdapterDialog adapterCasefile;
	public static String[] valuesageCasefile = new String[] { "CCCC" };
	public static ArrayList<String> valuesIdCasefile = new ArrayList<String>();
	
	public static ArrayList<String> arrLanguageId = new ArrayList<String>();



	private int year;
	private int month;
	private int day;
	public ProgressBar progressbar_sign_up;
	private EditText btn_circonstance_miss, txt_first_name, txt_last_name, txt_user_name, txt_hair
	,txt_eyes,txt_character,txt_facebook;
	
	static final int DATE_DIALOG_ID = 999;
	
    //************************CREATE DIALOG****************************
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		}
		return null;
	}
	//****************INIT**************************************
	public void init() {
		isUpdate = false;
		btn_case_file = (Button) findViewById(R.id.txt_case_file);
		btn_case_file.setText("Dossier no");
		txt_first_name = (EditText) findViewById(R.id.txt_first_name);
		txt_last_name = (EditText) findViewById(R.id.txt_last_name);
		btn_circonstance_miss = (EditText) findViewById(R.id.btn_circonstance_miss);
		txt_user_name = (EditText) findViewById(R.id.txt_user_name);
		txt_hair = (EditText) findViewById(R.id.txt_hair);
		txt_eyes = (EditText) findViewById(R.id.txt_eyes);
		txt_character = (EditText) findViewById(R.id.txt_character);
		txt_facebook = (EditText) findViewById(R.id.txt_facebook);
		
		btn_selecte_country = (Button) findViewById(R.id.btn_selecte_country);
		btn_selecte_province = (Button) findViewById(R.id.btn_selecte_province);
		txt_date = (Button) findViewById(R.id.txt_date);
		progressbar_sign_up = (ProgressBar) findViewById(R.id.progressbar_sign_up);
		
		
		TextView text_view_landing_page_header = (TextView) findViewById(R.id.text_view_landing_page_header);
        text_view_landing_page_header.setText("Add Victime");
		
		ImageView btn_setting = (ImageView) findViewById(R.id.image_setting);
		btn_setting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(), Settings.class);
	            startActivity(goToNextActivity);
			}
		});
		
		/**
		 * Kiem user da dang nhap hay chua
		 * 1. hein thi icon user
		 * 2. hien thi icon add victimes
		 */
		ImageView image_open_left_navigation = (ImageView) findViewById(R.id.image_open_left_navigation);
		ImageView icon_header_form = (ImageView) findViewById(R.id.icon_header_form);
		if(MainActivity.userId.equalsIgnoreCase("0")){
			image_open_left_navigation.setVisibility(View.VISIBLE);
			icon_header_form.setVisibility(View.GONE);
		}else{
			image_open_left_navigation.setVisibility(View.GONE);
			icon_header_form.setVisibility(View.VISIBLE);
		}
		
		image_open_left_navigation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(), MainActivity.class);
	            startActivity(goToNextActivity);
			}
		});
		
		icon_header_form.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(), FormFirst.class);
	            startActivity(goToNextActivity);
			}
		});
		
		
		
	}

	
	//**********************DATE PICKER**************************
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			txt_date.setText(new StringBuilder().append(year).append("-")
					.append(month + 1).append("-").append(day).append(" "));
			dis_date = txt_date.getText().toString();
			// set selected date into datepicker also

		}
	};
	//*********************NETWORK***********************************
	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	//*********** Called when the activity is first created. ***************/
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.form_1);
		
		init();
		txt_date.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}

		});

		btn_sign_up = (Button) findViewById(R.id.btn_sign_up);
		_disparition_add = (EditText) findViewById(R.id.disparition_add);
		btn_sign_up.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				disparition_add = _disparition_add.getText().toString();
				dis_date = txt_date.getText().toString();
				txt_case_file = btn_case_file.getText().toString();
				circonstance_miss = btn_circonstance_miss.getText().toString();
				name = txt_first_name.getText().toString();
				first_name = txt_last_name.getText().toString();
				nick_name = txt_user_name.getText().toString();
				hair_color = txt_hair.getText().toString();
				eyes_colors = txt_eyes.getText().toString();
				character = txt_character.getText().toString();
				facebook = txt_facebook.getText().toString();
				age = btn_selecte_age.getText().toString();
				language = btn_selecte_language.getText().toString();

				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				if (txt_case_file.matches("")) {
					alertDialogBuilder
							.setMessage("Please type case_file!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (countries_id.equals(null)) {
					alertDialogBuilder
							.setMessage("Please choose country!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (province_id.equals(null)) {
					alertDialogBuilder
							.setMessage("Please choose province!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (disparition_add.matches("")) {
					alertDialogBuilder
							.setMessage("Please type Disparition!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (circonstance_miss.matches("")) {
					alertDialogBuilder
							.setMessage("Please type circonstance miss!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (name.matches("")) {
					alertDialogBuilder
							.setMessage("Please type Name!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (first_name.matches("")) {
					alertDialogBuilder
							.setMessage("Please type First Name!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (nick_name.matches("")) {
					alertDialogBuilder
							.setMessage("Please type Nick Name!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (hair_color.matches("")) {
					alertDialogBuilder
							.setMessage("Please type Hair!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (eyes_colors.matches("")) {
					alertDialogBuilder
							.setMessage("Please type Eyes!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (age.equals(null)) {
					alertDialogBuilder
							.setMessage("Please choose Age!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if (language.equals(null)) {
					alertDialogBuilder
							.setMessage("Please choose language!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else {
					
					if (!isNetworkAvailable()) {

						Toast toast = Toast.makeText(getApplicationContext(),
								Common.MSG, Toast.LENGTH_SHORT);
						toast.show();
					} else {
						if(isUpdate)
							new Update().execute();
						else{
							Log.i("Save info",province_id +" || "+case_file_tmp);
							new Save().execute();
						}
					}

				}

			}
		});
		btn_selecte_age = (Button) findViewById(R.id.btn_selecte_age);
		btn_selecte_age.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				text_view_landing_page_header = (TextView) ageDialog
						.findViewById(R.id.text_view_landing_page_header);
				text_view_landing_page_header.setText("Age");
				// Display the WebView dialog
				ageDialog.show();
			}
		});
		// Create a new dialog
		ageDialog = new Dialog(this);
		// Remove the dialog's title
		ageDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Inflate the contents of this dialog with the Views defined at
		// 'webviewdialog.xml'
		ageDialog.setContentView(R.layout.age);
		// With this line, the dialog can be dismissed by pressing the back key
		ageDialog.setCancelable(true);

		// Get ListView object from xml
		listView = (ListView) ageDialog.findViewById(R.id.list);
		String[] values = new String[] { "1", "2", "3", "4", "5", "6", "7",
				"8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
				"19", "20", "21", "22", "23", "24", "25", "26", "27", "28",
				"29", "30", "31", "32", "33", "34", "35", "36", "37", "38",
				"39", "40", "41", "42", "43", "44", "45", "46", "47", "48",
				"49", "50", "51", "52", "53", "54", "55", "56", "57", "58",
				"59", "60", "61", "62", "63", "64", "65", "66", "67", "68",
				"69", "70", "71", "72", "73", "74", "75", "76", "77", "78",
				"79", "80", "81", "82", "83", "84", "85", "86", "87", "88",
				"89", "90", "91", "92", "93", "94", "95", "96", "97", "98",
				"99", "100" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.list_view_age, R.id.age, values);
		// Assign adapter to ListView
		listView.setAdapter(adapter);
		// ListView Item Click Listener
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				// TODO Auto-generated method stub

				// ListView Clicked item value
				String itemValue = (String) listView
						.getItemAtPosition(position);

				// Show Alert
				/*
				 * Toast.makeText(getApplicationContext(),
				 * "Position :"+itemPosition+"  ListItem : " +itemValue ,
				 * Toast.LENGTH_LONG) .show();
				 */
				btn_selecte_age.setText(itemValue);
				age = btn_selecte_age.getText().toString();
				ageDialog.dismiss();

			}

		});

		/**
		 * ============================================
		 */
		btn_selecte_language = (Button) findViewById(R.id.btn_selecte_language);
		btn_selecte_language.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				text_view_landing_page_header = (TextView) ageDialogLanguage
						.findViewById(R.id.text_view_landing_page_header);
				text_view_landing_page_header.setText("Spoken language");
				// Display the WebView dialog
				ageDialogLanguage.show();
			}
		});
		// Create a new dialog
		ageDialogLanguage = new Dialog(this);
		// Remove the dialog's title
		ageDialogLanguage.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Inflate the contents of this dialog with the Views defined at
		// 'webviewdialog.xml'
		ageDialogLanguage.setContentView(R.layout.language_dialog);
		// With this line, the dialog can be dismissed by pressing the back key
		ageDialogLanguage.setCancelable(true);

		// Get ListView object from xml
		listViewLanguage = (ListView) ageDialogLanguage.findViewById(R.id.list);
		String[] valuesageDialogLanguage = new String[] { " Francais ",
				" Anglais ", " Espagnol", " Autre" };
		arrLanguageId.add(0,"1");
		arrLanguageId.add(1,"2");
		arrLanguageId.add(2,"3");
		arrLanguageId.add(3,"4");
			
		ArrayAdapter<String> adapterageDialogLanguage = new ArrayAdapter<String>(
				this, R.layout.list_view_language, R.id.language,
				valuesageDialogLanguage);
		// Assign adapter to ListView
		listViewLanguage.setAdapter(adapterageDialogLanguage);
		// ListView Item Click Listener
		listViewLanguage.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				
				// ListView Clicked item value
				String itemValue = (String) listViewLanguage
						.getItemAtPosition(position);

				// Show Alert
				/*
				 * Toast.makeText(getApplicationContext(),
				 * "Position :"+itemPosition+"  ListItem : " +itemValue ,
				 * Toast.LENGTH_LONG) .show();
				 */
				btn_selecte_language.setText(itemValue);
				language = arrLanguageId.get(position);
				ageDialogLanguage.dismiss();

			}

		});

		/**
		 * ============================================
		 */
		btn_selecte_country.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				text_view_landing_page_header = (TextView) dialogCountry
						.findViewById(R.id.text_view_landing_page_header);
				text_view_landing_page_header.setText("Countries");
				if (!isNetworkAvailable()) {

					Toast toast = Toast.makeText(getApplicationContext(),
							Common.MSG, Toast.LENGTH_SHORT);
					toast.show();
				} else {
					
						new GetCountries().execute();
				}

				dialogCountry.show();

			}
		});
		// Create a new dialog
		dialogCountry = new Dialog(this);
		// Remove the dialog's title
		dialogCountry.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Inflate the contents of this dialog with the Views defined at
		// 'webviewdialog.xml'
		dialogCountry.setContentView(R.layout.countries_dialog);
		// With this line, the dialog can be dismissed by pressing the back key
		dialogCountry.setCancelable(true);
		// Get ListView object from xml
		listviewCountry = (ListView) dialogCountry.findViewById(R.id.list);

		/**
		 * ============================================
		 */
		btn_selecte_province.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {				
					
					if (!isNetworkAvailable()) {
						
						Toast.makeText(getApplicationContext(),Common.MSG, Toast.LENGTH_SHORT).show();
						
					} else {
						if(btn_selecte_country.getText().toString().matches(""))
							Toast.makeText(getApplicationContext(),"Please select Country", Toast.LENGTH_SHORT).show();
						else {
							text_view_landing_page_header = (TextView) dialogProvince.findViewById(R.id.text_view_landing_page_header);
							text_view_landing_page_header.setText("City");
							new GetCities().execute();
							dialogProvince.show();
						}
					}						

			}
		});
		// Create a new dialog
		dialogProvince = new Dialog(this);
		// Remove the dialog's title
		dialogProvince.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Inflate the contents of this dialog with the Views defined at
		// 'webviewdialog.xml'
		dialogProvince.setContentView(R.layout.countries_dialog);
		// With this line, the dialog can be dismissed by pressing the back key
		dialogProvince.setCancelable(true);
		// Get ListView object from xml
		listviewProvince = (ListView) dialogProvince.findViewById(R.id.list);
		

		/**
		 * =============CASE FILE===============================
		 */
		// Create a new dialog
		dialogCasefile = new Dialog(this);
		// Remove the dialog's title
		dialogCasefile.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Inflate the contents of this dialog with the Views defined at
		// 'webviewdialog.xml'
		dialogCasefile.setContentView(R.layout.countries_dialog);
		// With this line, the dialog can be dismissed by pressing the back key
		dialogCasefile.setCancelable(true);
		// Get ListView object from xml
		listviewCasefile = (ListView) dialogCasefile.findViewById(R.id.list);
		btn_case_file.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				text_view_landing_page_header = (TextView) dialogCasefile
						.findViewById(R.id.text_view_landing_page_header);
				text_view_landing_page_header.setText("Case file");
				if (!isNetworkAvailable()) {

					Toast toast = Toast.makeText(getApplicationContext(),
							Common.MSG, Toast.LENGTH_SHORT);
					toast.show();
				} else {
					new GetCasefile().execute();
				}

				dialogCasefile.show();

			}
		});
		
		if(!isNetworkAvailable()){
	    	  CharSequence text = "Please turn of wifi or 3G";
	    	  Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
	    	  toast.show();
	      }else{
	    	  new GetCaseTmp().execute();
	      }

	}

	public static JSONObject jsonobjecttmp;
    public static JSONArray jsonarraytmp;
    public static String  jotmp;
    public static boolean strErrortmp = true;
    ArrayList<HashMap<String, String>> arraylisttmp;
	private class GetCaseTmp extends AsyncTask<Void, Void, Void> {
		   
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }
 
        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylisttmp = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            
            jsonobjecttmp = JSONfunctions.getJSONfromURL("http://gosnoopers.com/victimes/app/getCaseFileAuto/author/"+MainActivity.userId);

            try {
                // Locate the array name in JSON
                //jsonarray = jsonobject.getJSONArray("data");
            	jotmp = jsonobjecttmp.getString("case_file");        	  

                strErrortmp = jsonobjecttmp.getBoolean("error");
                
                
               
                
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }
 
        @Override
        protected void onPostExecute(Void args) {
      	  
        	EditText data_case_file_tmp = (EditText) findViewById(R.id.case_file_tmp);
        	data_case_file_tmp.setText(jotmp);

      	  
      	  
      	  
      	  
            
        }
    }
	
	// ******************************GET CITIES*****************************
	private class GetCities extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array

			// Retrieve JSON Objects from the given URL address
			Log.i("URLCITI", URLCITIES);
			jsonobjectCities = JSONfunctions.getJSONfromURL(URLCITIES);

			try {
				// Locate the array name in JSON
				jsonarrayCities = jsonobjectCities.getJSONArray("data");

				boolean strError = jsonobjectCities.getBoolean("error");
				String message = jsonobjectCities.getString("message");
				if (!strError) {
					valuesageCities = new String[jsonarrayCities.length()];
					for (int i = 0; i < jsonarrayCities.length(); i++) {
						// HashMap<String, String> map = new HashMap<String,
						// String>();
						jsonobjectCities = jsonarrayCities.getJSONObject(i);
						// Retrive JSON Objects

						valuesageCities[i] = jsonobjectCities.getString("Name");
						arrCitiesId.add(jsonobjectCities.getString("Id"));
					}

				} else {
					valuesageCities = new String[100];
					Toast toast = Toast.makeText(getApplicationContext(),
							message, Toast.LENGTH_SHORT);
					toast.show();
				}

			} catch (JSONException e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			ArrayAdapter<String> adapterageDialogCities = new ArrayAdapter<String>(
					FormFirst.this, R.layout.list_view_language, R.id.language,
					valuesageCities);
			// Assign adapter to ListView

			listviewProvince.setAdapter(adapterageDialogCities);
			listviewProvince.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					
					

					// ListView Clicked item value
					String itemValue = (String) listviewProvince
							.getItemAtPosition(position);

					btn_selecte_province.setText(itemValue);
					province_id = arrCitiesId.get(position);
					dialogProvince.dismiss();

				}

			});

		}
	}

	// *******************GET COUNTRY*********************************
	private class GetCountries extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array
			arraylistCountries = new ArrayList<HashMap<String, String>>();
			// Retrieve JSON Objects from the given URL address

			jsonobjectCountries = JSONfunctions
					.getJSONfromURL("http://gosnoopers.com/country/getAllCountries");

			try {
				// Locate the array name in JSON
				jsonarrayCountries = jsonobjectCountries.getJSONArray("data");
				boolean strError = jsonobjectCountries.getBoolean("error");
				String message = jsonobjectCountries.getString("message");
				if (!strError) {
					valuesageCountry = new String[jsonarrayCountries.length()];
					for (int i = 0; i < jsonarrayCountries.length(); i++) {
						// HashMap<String, String> map = new HashMap<String,
						// String>();
						jsonobjectCountries = jsonarrayCountries
								.getJSONObject(i);
						// Retrive JSON Objects

						valuesageCountry[i] = jsonobjectCountries
								.getString("Name");
						arrCountryId.add(jsonobjectCountries.getString("Id"));
					}

				} else {
					valuesageCountry = new String[100];
					Toast toast = Toast.makeText(getApplicationContext(),
							message, Toast.LENGTH_SHORT);
					toast.show();
				}

			} catch (JSONException e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			ArrayAdapter<String> adapterageDialogCountries = new ArrayAdapter<String>(
					FormFirst.this, R.layout.list_view_language, R.id.language,
					valuesageCountry);
			// Assign adapter to ListView
			listviewCountry.setAdapter(adapterageDialogCountries);
			// ListView Item Click Listener
			listviewCountry.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View view,
						int position, long id) {
					
					// ListView Clicked item index
					

					// ListView Clicked item value
					String itemValue = (String) listviewCountry
							.getItemAtPosition(position);

					btn_selecte_country.setText(itemValue);
					URLCITIES = "http://gosnoopers.com/province/getProvinceByCountryId?CountryId="+arrCountryId.get(position);
					countries_id = arrCountryId.get(position);
					btn_selecte_province.setText("");
					dialogCountry.dismiss();

				}

			});
		}
	}
	
	// *********************get case file*********************
		private class GetCasefile extends AsyncTask<Void, Void, Void> {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();			
			}

			@Override
			protected Void doInBackground(Void... params) {
				// Create an array
				arraylistCasefile = new ArrayList<HashMap<String, String>>();
				// Retrieve JSON Objects from the given URL address

				jsonobjectCasefile = JSONfunctions
						.getJSONfromURL("http://gosnoopers.com/victimes/app/getAllCaseFile/author/"+MainActivity.userId);

				try {
					// Locate the array name in JSON
					jsonarrayCasefile = jsonobjectCasefile.getJSONArray("data");
					boolean strError = jsonobjectCasefile.getBoolean("error");
					String message = jsonobjectCasefile.getString("message");
					if (!strError) {
						valuesageCasefile = new String[jsonarrayCasefile.length()];
						
						for (int i = 0; i < jsonarrayCasefile.length(); i++) {
							// HashMap<String, String> map = new HashMap<String,
							// String>();
							jsonobjectCasefile = jsonarrayCasefile.getJSONObject(i);
							// Retrive JSON Objects

							valuesageCasefile[i] = jsonobjectCasefile.getString("case_file");
							valuesIdCasefile.add(jsonobjectCasefile.getString("id"));
						}

					} else {
						valuesageCasefile = new String[100];
						Toast toast = Toast.makeText(getApplicationContext(),
								message, Toast.LENGTH_SHORT);
						toast.show();
					}

				} catch (JSONException e) {
					Log.e("Error", e.getMessage());
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void args) {

				ArrayAdapter<String> adapterageDialogCasefile = new ArrayAdapter<String>(
						FormFirst.this, R.layout.list_view_language, R.id.language,
						valuesageCasefile);
				// Assign adapter to ListView
				listviewCasefile.setAdapter(adapterageDialogCasefile);
				// ListView Item Click Listener
				listviewCasefile.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View view,
							int position, long id) {
											
						// ListView Clicked item value
						String itemValue = (String) listviewCasefile.getItemAtPosition(position);
						victim_id_new = valuesIdCasefile.get(position);
						btn_case_file.setText(itemValue);
//						Log.i("item value",itemValue);
						if(itemValue.equals("Dossier no")){
							isUpdate = false;
							TextView text_view_landing_page_header = (TextView) findViewById(R.id.text_view_landing_page_header);
					        text_view_landing_page_header.setText("Add Victime");
					        btn_selecte_country.setText("");
							btn_selecte_province.setText("");
							txt_date.setText("");
							_disparition_add.setText("");
							btn_circonstance_miss.setText("");
							txt_first_name.setText("");
							txt_last_name.setText("");
							txt_user_name.setText("");
							btn_selecte_age.setText("");
							btn_selecte_language.setText("");
							txt_hair.setText("");
							txt_eyes.setText("");
							txt_character.setText("");
							txt_facebook.setText("");
							EditText tmp_case_file_tmp = (EditText) findViewById(R.id.case_file_tmp);
							tmp_case_file_tmp.setVisibility(View.VISIBLE);
						}else{
							isUpdate = true;
							TextView text_view_landing_page_header = (TextView) findViewById(R.id.text_view_landing_page_header);
							text_view_landing_page_header.setText("Update Victime");
							EditText tmp_case_file_tmp = (EditText) findViewById(R.id.case_file_tmp);
							tmp_case_file_tmp.setVisibility(View.GONE);
							new GetInfoVictime().execute();
						}
						dialogCasefile.dismiss();	

					}

				});
			}
		}
		
		// ******************************GET INFO VICTIME************************
		private class GetInfoVictime extends AsyncTask<Void, Void, Void> {
			JSONObject jo,jo1;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				progressbar_sign_up.setVisibility(View.VISIBLE);
				btn_sign_up.setEnabled(false);
			}

			@Override
			protected Void doInBackground(Void... s) {

				jo = JSONfunctions
						.getJSONfromURL("http://gosnoopers.com/victimes/app/detail?id="	+ victim_id_new);
				Log.i("DATA: =>","http://gosnoopers.com/victimes/app/detail?id="	+ victim_id_new);
				try {

					jo1 = jo.getJSONObject("data");
					checkError = jo.getBoolean("error");
					aPhotoForm = jo1.getJSONArray("photos");
					FormSecond.imageArr.clear();
					for (int i = 0; i < aPhotoForm.length(); i++) {
						FormSecond.imageArr.add(new ImageLoader(context).getBitmap(aPhotoForm.getString(i)));
					}
					//Log.i("ket qua test",aPhotoForm.toString());

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void args) {
				
				if (!checkError) {
//					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();

					// Log.i("DATA@@@@@@: =>",jsonobject2.toString());

					try {

						btn_selecte_country.setText(jo1.getString("coutry_display"));
						btn_selecte_province.setText(jo1.getString("province_display"));
						txt_date.setText(jo1.getString("dis_date"));
						_disparition_add.setText(jo1.getString("disparition_add"));
						btn_circonstance_miss.setText(jo1.getString("circonstance_miss"));
						txt_first_name.setText(jo1.getString("first_name"));
						txt_last_name.setText(jo1.getString("name"));
						txt_user_name.setText(jo1.getString("nick_name"));
						btn_selecte_age.setText(jo1.getString("age"));
						btn_selecte_language.setText(jo1.getString("language_display"));
						txt_hair.setText(jo1.getString("hair_color"));
						txt_eyes.setText(jo1.getString("eyes_colors"));
						txt_character.setText(jo1.getString("character"));
						txt_facebook.setText(jo1.getString("facebook"));						
						countries_id =  jo1.getString("countries_id");
						URLCITIES = "http://gosnoopers.com/province/getProvinceByCountryId?CountryId="+countries_id;
						province_id =  jo1.getString("province_id");
						
						

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {

					Toast.makeText(getApplicationContext(), "Error!",
							Toast.LENGTH_SHORT).show();
				}
				progressbar_sign_up.setVisibility(View.GONE);
				btn_sign_up.setEnabled(true);
			}
		}	

	ProgressDialog mProgressDialog;
	ProgressBar pb;
	ArrayList<HashMap<String, String>> arraylist;
	static String ID = "id";
	static String NAME = "name";
	static String ALIAS = "alias";
	public static JSONObject jsonobject;
	public static JSONArray jsonarray;
	public static String victim_id_new = "0";
	ListView list;
	boolean checkError = false;
	String message = "";
	// ***************************SAVE********************************
	private class Save extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pb = (ProgressBar) findViewById(R.id.progressbar_sign_up);
			pb.setVisibility(View.VISIBLE);
			btn_sign_up.setEnabled(false);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array
			arraylist = new ArrayList<HashMap<String, String>>();
			// Retrieve JSON Objects from the given URL address
			EditText tmp_case_file_tmp = (EditText) findViewById(R.id.case_file_tmp);
			case_file_tmp = tmp_case_file_tmp.getText().toString();
			
			Button data_btn_selecte_province = (Button) findViewById(R.id.btn_selecte_province);
			province_id = data_btn_selecte_province.getText().toString();
			String paramsURL = "?amberalert="
					+ amberalert
					+ "&dis_date="
					+ dis_date
					+ "&disparition_add="
					+ disparition_add
					+ "&circonstance_miss="
					+ circonstance_miss
					+ "&name="
					+ name
					+ "&first_name="
					+ first_name
					+ "&nick_name="
					+ nick_name
					+ "&age="
					+ age
					+ "&language="
					+ language
					+ "&hair_color="
					+ hair_color
					+ "&eyes_colors="
					+ eyes_colors
					+ "&character="
					+ character
					+ "&any_health_condition="
					+ any_health_condition
					+ "&handicap="
					+ handicap
					+ "&transport="
					+ transport
					+ "&any_scars="
					+ any_scars
					+ "&tattoo="
					+ tattoo
					+ "&something_special="
					+ something_special
					+ "&defferent_interest="
					+ defferent_interest
					+ "&life_style="
					+ life_style
					+ "&p_weight="
					+ 0
					+ "&p2_weight="
					+ 0
					+ "&k_weight="
					+ 0
					+ "&k2_weight="
					+ 0
					+ "&f_tall="
					+ 0
					+ "&f2_tall="
					+ 0
					+ "&m2_tall="
					+ 0
					+ "&m_tall="
					+ 0
					+ "&date_r="
					+ date_r
					+ "&author="
					+ author
					+ "&countries_id="
					+ countries_id
					+ "&province_id="
					+ province_id
					+ "&facebook="
					+ facebook
					+ "&case_file_tmp="+case_file_tmp+"&latitude=atitude&address=Google Maps&longtitude=Longtitude&id_image=";
			Log.d("paramsURL", "Json get post: " + paramsURL);
			jsonobject = JSONfunctions.executeUrlWithOption(true,"http://gosnoopers.com/victimes/app/add", paramsURL, false);
			Log.d("FORM FIRST", "Json get post: " + jsonobject);
			try {
				JSONObject jsonData =  jsonobject.getJSONObject("data");
				JSONObject jsonMaps = jsonData.getJSONObject("maps");
				victim_id_new = jsonobject.getString("id");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			Log.i("SAVE VIC",victim_id_new);
			pb = (ProgressBar) findViewById(R.id.progressbar_sign_up);
			pb.setVisibility(View.GONE);
			btn_sign_up.setEnabled(true);
			if(!checkError){
				Intent goToNextActivity = new Intent(getApplicationContext(), FormSecond.class);
				goToNextActivity.putExtra(FormSecond.KEY_ID_VICTIM, victim_id_new);
                startActivity(goToNextActivity);
			}else{
				
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				alertDialogBuilder
				.setMessage(message)
				.setCancelable(false)
				.setNegativeButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			}
		}
	}
	
	// ***************************UPDATE********************************
		private class Update extends AsyncTask<Void, Void, Void> {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				pb = (ProgressBar) findViewById(R.id.progressbar_sign_up);
				pb.setVisibility(View.VISIBLE);
				btn_sign_up.setEnabled(false);
			}

			@Override
			protected Void doInBackground(Void... params) {
				// Create an array
				arraylist = new ArrayList<HashMap<String, String>>();
				// Retrieve JSON Objects from the given URL address
				Button data_btn_selecte_province = (Button) findViewById(R.id.btn_selecte_province);
				province_id = data_btn_selecte_province.getText().toString();
				
				String paramsURL = "?amberalert="
						+ amberalert
						+ "&dis_date="
						+ txt_date.getText().toString()
						+ "&disparition_add="
						+ _disparition_add.getText().toString()
						+ "&circonstance_miss="
						+ btn_circonstance_miss.getText().toString()
						+ "&name="
						+ txt_last_name.getText().toString()
						+ "&first_name="
						+ txt_first_name.getText().toString()
						+ "&nick_name="
						+ txt_user_name.getText().toString()
						+ "&age="
						+ btn_selecte_age.getText().toString()
						+ "&language="
						+ language
						+ "&hair_color="
						+ txt_hair.getText().toString()
						+ "&eyes_colors="
						+ txt_eyes.getText().toString()
						+ "&character="
						+ txt_character.getText().toString()
						+ "&any_health_condition="
						+ any_health_condition
						+ "&handicap="
						+ handicap
						+ "&transport="
						+ transport
						+ "&any_scars="
						+ any_scars
						+ "&tattoo="
						+ tattoo
						+ "&something_special="
						+ something_special
						+ "&defferent_interest="
						+ defferent_interest
						+ "&life_style="
						+ life_style
						+ "&p_weight="
						+ 0
						+ "&p2_weight="
						+ 0
						+ "&k_weight="
						+ 0
						+ "&k2_weight="
						+ 0
						+ "&f_tall="
						+ 0
						+ "&f2_tall="
						+ 0
						+ "&m2_tall="
						+ 0
						+ "&m_tall="
						+ 0
						+ "&date_r="
						+ date_r
						+ "&author="
						+ MainActivity.userId
						+ "&countries_id="
						+ countries_id
						+ "&province_id="
						+ province_id
						+ "&facebook="
						+ txt_facebook.getText().toString()
						+ "&case_file_tmp="+btn_case_file.getText().toString()+"&latitude=atitude&address=Google Maps&longtitude=Longtitude&id_image=";
				Log.d("paramsURL", "Json get post: " + paramsURL);
				jsonobject = JSONfunctions.executeUrlWithOption(true,"http://gosnoopers.com/victimes/app/edit?id="+victim_id_new, paramsURL, false);
				Log.d("FORM FIRST", "Json get post: " + jsonobject);
				try {
					checkError = jsonobject.getBoolean("error");
					message = jsonobject.getString("message");
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void args) {
				Log.i("Update vic",victim_id_new);
				pb = (ProgressBar) findViewById(R.id.progressbar_sign_up);
				btn_sign_up.setEnabled(true);
				pb.setVisibility(View.GONE);
				if(!checkError){
					Intent goToNextActivity = new Intent(getApplicationContext(), FormSecond.class);
					goToNextActivity.putExtra(FormSecond.KEY_ID_VICTIM, victim_id_new);
	                startActivity(goToNextActivity);
				}else{
					Toast.makeText(getApplicationContext(), message,
							Toast.LENGTH_SHORT).show();
				}
			}
		}

}